'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Search } from 'lucide-react';
import { OrderDialog } from '@/components/orders/order-dialog';

interface Order {
  orderId: string; // 修改为 string 类型
  openId: string;
  goodsId: number;
  orderTime: string;
  orderState: number;
  userName: string;
  goodsName: string;
  goodsPrice: number;
  goodsImage: string;
  goodsAddress: string;
  tel: string;
  customerName: string;
  trading: number;
}

export default function OrdersPage() {
  const [orders, setOrders] = useState<Order[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);

  useEffect(() => {
    const fetchOrders = async () => {
      try {
        setIsLoading(true);
        const response = await fetch("/api/orders");

        if (!response.ok) {
          throw new Error("获取订单数据失败");
        }

        const data = await response.json();
        setOrders(data.orders);
      } catch (error) {
        console.error("获取订单数据失败:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchOrders();
  }, []);

  // 过滤订单
  const filteredOrders = orders.filter(
    (order) =>
      order.goodsName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.userName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.goodsAddress.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.customerName.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 获取订单状态文本
  const getOrderStatusText = (status: number) => {
    switch (status) {
      case 0:
        return "待付款";
      case 1:
        return "待发货";
      case 2:
        return "待收货";
      case 3:
        return "已完成";
      case 4:
        return "已取消";
      default:
        return "未知状态";
    }
  };

  // 获取订单状态样式
  const getOrderStatusVariant = (status: number) => {
    switch (status) {
      case 0:
        return "secondary";
      case 1:
        return "default";
      case 2:
        return "default";
      case 3:
        return "success";
      case 4:
        return "destructive";
      default:
        return "secondary";
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const handleOrderSave = (updatedOrder: Order) => {
    setOrders(orders.map(order => 
      order.orderId === updatedOrder.orderId ? updatedOrder : order
    ));
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">订单管理</h1>
        <p className="text-muted-foreground">查看和管理平台订单信息</p>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-xl font-bold">订单列表</CardTitle>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="搜索订单..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Button variant="outline">导出</Button>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center items-center h-[400px]">
              <p>加载中...</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>订单ID</TableHead>
                  <TableHead>商品信息</TableHead>
                  <TableHead>价格</TableHead>
                  <TableHead>买家</TableHead>
                  <TableHead>下单时间</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredOrders.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center h-24">
                      未找到匹配的订单
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredOrders.map((order) => (
                    <TableRow key={order.orderId}>
                      <TableCell>{order.orderId}</TableCell>
                      <TableCell className="font-medium">
                        <div className="flex items-center space-x-2">
                          <img
                            src={order.goodsImage}
                            alt={order.goodsName}
                            className="h-10 w-10 rounded object-cover"
                          />
                          <span>{order.goodsName}</span>
                        </div>
                      </TableCell>
                      <TableCell>¥{order.goodsPrice.toFixed(2)}</TableCell>
                      <TableCell>{order.userName}</TableCell>
                      <TableCell>{formatDate(order.orderTime)}</TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            getOrderStatusVariant(order.orderState) as any
                          }
                        >
                          {getOrderStatusText(order.orderState)}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <Button 
                          variant="ghost" 
                          size="sm"
                          onClick={() => {
                            setSelectedOrder(order);
                            setDialogOpen(true);
                          }}
                        >
                          查看详情
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <OrderDialog
        order={selectedOrder}
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        onSave={handleOrderSave}
      />
    </div>
  );
}
